package com.lanmei.group.weixin.controller.admin;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.lanmei.group.weixin.interceptor.ManagerInterceptor;
import com.lanmei.group.weixin.interceptor.SiteInterceptor;
import com.lanmei.group.weixin.utils.ShiroUtil;
import com.lanmei.group.weixin.utils.StringUtil;
@Clear(ManagerInterceptor.class)
public class AdminController extends Controller {
	
	public void index(){
		render("login.jsp");
	}
	public void login(){
		String loginName = getPara("loginName");
		String pwd = getPara("pwd");
		if(StringUtil.isEmpty(loginName)||StringUtil.isEmpty(pwd)){
			setAttr("msg", "用户名或密码不可为空");
			render("login.jsp");
			return;
		}
		Subject subject = SecurityUtils.getSubject();		
		UsernamePasswordToken token = new UsernamePasswordToken(loginName, StringUtil.MD5(pwd));
		try {
			subject.login(token);
		} catch (UnknownAccountException e1) {
			e1.printStackTrace();
			setAttr("msg", "用户名或密码不正确！");
			render("login.jsp");
			return;
		}catch (DisabledAccountException e2) {
			e2.printStackTrace();
			setAttr("msg", "用户已被禁用！");
			render("login.jsp");
			return;
		}catch (Exception e3) {
			e3.printStackTrace();
		}
		if(subject.isAuthenticated()){
			this.redirect("/admin/toIndex");
			System.out.println("loginName:"+ShiroUtil.getLoginName());
			return;
		}
		render("login.jsp");
	}
	public void welcome(){
		render("welcome.jsp");
	}
	@RequiresRoles(value = { "admin","user" },logical=Logical.OR)
	public void toIndex(){
		render("index.jsp");
	}
	@RequiresAuthentication
	public void logout(){
		try {
			ShiroUtil.logout();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.redirect("/admin/index");
	}
}
